import { defineStore } from 'pinia'
import user from "@/api/user"
import { useSeekerStore } from './seeker'
import { useRecruiterStore } from './recruiter'
import { useAdminStore } from './admin'
import { useAuthStore } from '.'

export const useUserStore = defineStore('user', {
  state: () => ({
    user_id: null,
    username: null,
    role: null,
    avatar_url: null,
  }),
  getters: {
  },
  actions: {
    setAvatar(avatar_url) {
      this.avatar_url = avatar_url
    },
    async getUserInfo() {
      try {
        const res = await user.getUserInfo()
        const { user_id, username, role, avatar_url } = res.data || {}
        this.user_id = user_id
        this.username = username
        this.role = role
        this.avatar_url = avatar_url
        if(role === 'seeker') {
          const seekerStore = useSeekerStore()
          seekerStore.getSeeker()
        }
        else if(role === 'recruiter') {
          const recruiterStore = useRecruiterStore()
          recruiterStore.getRecruiter()
        }
        else if(role === 'admin') {
          const adminStore = useAdminStore()
          adminStore.getAdmin()
        }
        //保存至storage
        useAuthStore().setRole(role)
        return Promise.resolve(res.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    resetUser() {
      this.$reset()
    },
  },
})
